import pandas as pd

from core.constant import *
from conf import conf
from tools.framework import datetime_str
from datetime import timedelta
import statistics

from core.map_const import IntervalMap


def gen_data_name(data_name_prefix: DataCategory, symbol=None, time_str=None):
    if time_str is None:
        time_str = datetime_str(data_name=True)
    else:
        time_str = time_str
    if symbol is not None:
        return conf.FileManager.f.value.join([data_name_prefix.value, symbol, time_str])
    else:
        return conf.FileManager.f.value.join([data_name_prefix.value, time_str])


def split_df_by_symbol(df: pd.DataFrame):
    """
    如果DataFrame中存在'symbol'列，则按此列的值拆分DataFrame。
    否则，返回原始DataFrame。

    :param df: 输入的DataFrame。
    :return: 字典，键为'symbol'的值，值为对应的DataFrame，或者原始DataFrame。
    """

    def drop_repeat_index(df_f):
        """
        移除DataFrame中重复的索引行，但保留每组重复索引中的最后一行。
        """
        return_df = df_f.reset_index().drop_duplicates(subset='datetime', keep='last').set_index('datetime', drop=True)
        return return_df

    if 'symbol' in df.columns:
        # 按"symbol"的值拆分DataFrame
        df_dc = {symbol: drop_repeat_index(sub_df.drop(columns=['symbol'])) for symbol, sub_df in df.groupby('symbol')}
        return df_dc
    else:
        # 如果"symbol"列不存在
        return {Model.DefaultSymbol.value: drop_repeat_index(df)}


def merge_columns(data_columns_ls):
    # 需要用简写合并显示的字段
    merge_columns = ["datetime", "open", "high", "low", "close", "volume"]
    merge_columns_ls = [""]
    merge_str = ""
    for column in data_columns_ls:
        if column in merge_columns:
            merge_str += column[0]
        else:
            merge_columns_ls.append(column)

    merge_columns_ls[0] = merge_str

    return merge_columns_ls


def data_df_interval(data_df):
    # 读取数据文件的前20组
    temp_df = data_df.head(20)
    temp_index_ls = temp_df.index.tolist()
    temp_timedelta_ls = []
    for i in range(len(temp_index_ls) - 1):
        temp_timedelta_ls.append(temp_index_ls[i + 1] - temp_index_ls[i])
    mode_value: timedelta = statistics.mode(temp_timedelta_ls)
    # 根据timedelta通过IntervalMap反向获取相应的Interval实例
    interval_ins = None
    interval_val = None
    for k, v in IntervalMap.items():
        if v == mode_value:
            interval_ins = v
            interval_val = k
            break
    if interval_ins is None:
        raise ValueError("获取数据文件的Interval实例失败。")

    return interval_val


def file_info_log_str(describe_all_dc):
    """针对性处理file info文本信息"""
    # 按最后修改时间对数据进行排序
    sorted_describe_dict = dict(sorted(describe_all_dc.items(), key=lambda x: x[1].name, reverse=True))
    # sorted_describe_dict = describe_all_dc
    # 合并文件信息
    info = ""
    for i, (key, value) in enumerate(sorted_describe_dict.items()):
        info += " " * 10 + "\n"
        info += value.get_string()

    return info

